package com.kaesar.leetcode.LeetCode_001_050;

import java.util.*;

public class LeetCode_039 {
    /**
     * 暴力破解法
     *
     * @param candidates
     * @param target
     * @return
     */
    public static List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> result = new ArrayList<>();
        Queue<List<Integer>> allPossibleCombinations = new LinkedList<>();
        for (int candidate : candidates) {
            List<Integer> onePossibleCombination = new ArrayList<>();
            onePossibleCombination.add(candidate);
            allPossibleCombinations.add(onePossibleCombination);
        }
        while (!allPossibleCombinations.isEmpty()) {
            List<Integer> temp = allPossibleCombinations.poll();
            int sum = 0;
            for (Integer num : temp) {
                sum += num;
            }
            if (sum == target) {
                result.add(temp);
            } else if (sum < target) {
                for (int candidate : candidates) {
                    // List复制方法
                    List<Integer> toAdd = new ArrayList<Integer>(Arrays.asList(new Integer[temp.size()]));
                    Collections.copy(toAdd, temp);
                    toAdd.add(candidate);
                    allPossibleCombinations.add(toAdd);
                }
            }
        }

        List<List<Integer>> result1 = new ArrayList<>();
        for (int i = 0; i < result.size(); i++) {
            boolean isRepeated = false;
            List<Integer> one = result.get(i);
            Collections.sort(one);
            for (int j = i + 1; j < result.size(); j++) {
                List<Integer> two = result.get(j);
                Collections.sort(two);
                if (one.size() != two.size()) {
                    continue;
                }
                boolean equals = true;
                for (int x = 0; x < one.size(); x++) {
                    if (!one.get(x).equals(two.get(x))) {
                        equals = false;
                        continue;
                    }
                }
                if (equals) {
                    isRepeated = true;
                }
            }
            if (!isRepeated) {
                result1.add(one);
            }
        }

        return result1;
    }

    public static void main(String[] args) {
        int[] candidates = new int[]{8, 10, 6, 3, 4, 12, 11, 5, 9};
        for (List<Integer> integers : combinationSum(candidates, 28)) {
            for (Integer integer : integers) {
                System.out.print(integer + " ");
            }
            System.out.println();
        }
    }
}
